package com.jiashihui.schema_lgorithm.java.properties.util;

import com.jiashihui.schema_lgorithm.common.ExceptionEnum;
import com.jiashihui.schema_lgorithm.exception.AncbException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 * exe文件执行
 */
public class ExecuteUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExecuteUtil.class);

    private ExecuteUtil(){}

    /**
     * 执行exe文件
     * @throws AncbException
     */
    public static void execute(String filePath, String fileName) throws AncbException {
        File dir = new File(filePath);
        String command = "cmd.exe   /C   start   " + filePath + fileName;
        // 运行bat文件
        try {
            Process process = Runtime.getRuntime().exec(command, null, dir);
            int isRunningExitCode = process.waitFor();
            if(isRunningExitCode != 0){
                throw new AncbException(ExceptionEnum.NOT_FOUND_FILE_EXCEPTION.getCode(), ExceptionEnum.NOT_FOUND_FILE_EXCEPTION.getMsg());
            }
        } catch (Exception e) {
            LOGGER.error("执行bat文件失败.", e);
            throw new AncbException(ExceptionEnum.EXECUTE_BAT_EXCEPTION.getCode(), e);
        }
    }

    /**
     * 关闭cmd.exe窗口
     * @throws AncbException
     */
    public static void killProcess() throws AncbException, InterruptedException {
        try {
            Runtime.getRuntime().exec("cmd.exe /C start wmic process where name='cmd.exe' call terminate");
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            LOGGER.error("阻塞线程问题.", e);
            Thread.currentThread().interrupt();
            throw new AncbException(ExceptionEnum.INTERRUPTE_EXCEPTION.getCode(), e);
        } catch (IOException e) {
            LOGGER.error("关闭cmd.exe窗口异常.", e);
            throw new AncbException(ExceptionEnum.CLOSE_CMD_EXCEPTION.getCode(), e);
        }
    }
}
